import React, { PureComponent, Fragment } from 'react';
import moment from 'moment';
import { connect } from 'dva';
import {
  Button,
  Tag,
  Modal,
  Form,
  message,
  Table,
  Radio,
  Input,
  Icon,
  Drawer,
  Row,
  Tree,
  Switch,
  Progress, DatePicker, Badge, Select, Tooltip,
} from 'antd';
import MyPagination from '@/components/MyPagination';
import find from 'lodash/find';
import Loading from '@/components/Loading';
import debounce from 'lodash/debounce';
import Detail from './../Meters/Detail';
import ReactDataGrid from 'react-data-grid';
import ReactEcharts from 'echarts-for-react';
import {renderValveOpen, formateObjToParamStr, formateObjToParamStr2, download, getEW} from '@/utils/utils';
import forEach from 'lodash/forEach';
import request from '@/utils/request';
import config from '../../config/config';
import AreaMap from "@/components/AreaMap";

const { TreeNode, DirectoryTree } = Tree;
const FormItem = Form.Item;
const { confirm } = Modal;
const Option = Select.Option;

const RadioButton = Radio.Button;

const RadioGroup = Radio.Group;

@connect(({ devices, loading, global }) => ({
  devices,
  global,
  loading: loading.models.devices,
}))
@Form.create()
class BasicList extends PureComponent {
  constructor(props) {
    super(props);
    this.permissions = JSON.parse(sessionStorage.getItem('permissions'));
    this.state = {
      showAddBtn: find(this.permissions, { name: 'device_add_and_edit' }),
      showdelBtn: find(this.permissions, { name: 'device_delete' }),
      showPasswordBtn: find(this.permissions, { name: 'user_default_password_edit' }),
      user_password_reset: find(this.permissions, { name: 'user_password_reset' }),
      visible: false,
      done: false,
      page: 1,
      per_page: 30,
      username: '',
      editRecord: {},
      selectedRowKeys: [],
      all_vendors: [],
    };
  }


  componentDidMount() {

    const { dispatch } = this.props;
    const {
      devices: { pageLoaded, scrollData },
    } = this.props;
    console.log('pageLoaded', pageLoaded);
    const table = document.querySelector('.react-grid-Canvas');
    if (pageLoaded) {
      setTimeout(() => {
        table.scrollTop = scrollData.y;
        table.scrollLeft = scrollData.x;
      }, 0);

    } else {
      const {
        devices: { searchParams },
      } = this.props;
      console.log('searchParams', searchParams);
      dispatch({
        type: 'devices/fetch',
        payload: searchParams,
        callback: () => {
          const { dispatch } = this.props;
          dispatch({
            type: 'devices/changeLoaded',
          });
          dispatch({
            type: 'devices/changeTableY',
          });

          const {
            devices: { data },
          } = this.props;
          if (data.length > 0) {
            this.props.dispatch({
              type: 'devices/changeSelectRow',
              payload: {
                selectedIndex: [0],
                row: data[0],
              },
            });
          }


        },
      });
    }

    const that = this;
    request(`/all_vendors`, {
      method: 'GET',
    }).then((response) => {
      if (response.status === 200) {
        that.setState({
          all_vendors: response.data.data,
        });
      }

    });
    window.addEventListener('resize', this.resize);
    table.addEventListener('scroll', debounce(this.scroll, 150));
  }

  scroll = (e) => {
    console.log('scroll');
    const { dispatch } = this.props;
    dispatch({
      type: 'devices/changeScroll',
      payload: {
        x: e.target.scrollLeft,
        y: e.target.scrollTop,
      },
    });
  };

  resize = () => {
    const { dispatch } = this.props;

    // this.changeTableY();
    dispatch({
      type: 'devices/changeTableY',
    });
  };

  changeTableY = () => {
    console.log('top---------', document.querySelector('.bottom-analysis').getBoundingClientRect().top);
    this.setState({
      tableY: document.querySelector('.bottom-analysis').getBoundingClientRect().top -
        document.querySelector('.custom-small-table').getBoundingClientRect().top - 50,
    });
  };

  componentWillUnmount() {
    console.log('componentWillUnmount');
    window.removeEventListener('resize', this.resize);
    return;
    const table = document.querySelector('.ant-table-body');
    table.removeEventListener('scroll', debounce(this.scroll, 300));
  }

  handleSearch = (values, cb) => {
    console.log('handleSearch', values);
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: 'devices/fetch',
      payload: {
        ...values,
      },
      callback() {
        console.log('handleSearch callback');
        if (cb) cb();
        const {
          devices: { scrollData },
        } = that.props;
        const table = document.querySelector('.react-grid-Canvas');
        if(table){
          setTimeout(() => {
            table.scrollTop = 0;
            table.scrollLeft = scrollData.x;
          }, 0);
        }
      },
    });
  };

  renderSimpleForm() {
    const {
      devices: { searchParams },
    } = this.props;
    const form=this.props.form
    const getFieldDecorator=form.getFieldDecorator
    return (
      <Form layout="inline" className="search-form">
        <AreaMap form={form} searchParams={searchParams} getFieldDecorator={getFieldDecorator}/>
        <FormItem label={'日期'}>
          {getFieldDecorator('date', {
            initialValue: moment(searchParams.date),
          })(
            <DatePicker
              style={{ width: '120px' }}
              allowClear={false}
              //disabledDate={disabledDate}
              format="YYYY-MM-DD"
            />,
          )}
        </FormItem>

        <FormItem label="状态">
          {getFieldDecorator('status', {
            initialValue: searchParams.status,
          })(
            <Select style={{ width: '100px' }}>
              <Option value="0">全部</Option>
              <Option value="1">正常</Option>
              <Option value="-1">未上报</Option>
              <Option value="-2">漏报</Option>
              <Option value="-3">抄表失败</Option>
              <Option value="-4">错报</Option>
              <Option value="-5">接入异常</Option>
            </Select>,
          )}
        </FormItem>
        <FormItem label="是否已开户">
          {getFieldDecorator('opened_account', {
            initialValue: searchParams.opened_account,
          })(
            <Select style={{ width: '80px' }} allowClear >
              <Option  value={'1'}>已开户</Option>
              <Option  value={'-1'}>未开户</Option>
            </Select>,
          )}
        </FormItem>
        <FormItem label="水表厂商">
          {getFieldDecorator('vendor_id', {
            initialValue: searchParams.vendor_id,
          })(
            <Select style={{ width: '120px' }} allowClear>
              {
                this.state.all_vendors.map((item, index) => {
                  return <Option key={index} value={item.id}>{item.name}</Option>;
                })
              }
            </Select>,
          )}
        </FormItem>
        <FormItem label="水表号">
          {getFieldDecorator('meter_number', {
            initialValue: searchParams.meter_number,
          })(<Input style={{ width: '140px' }} placeholder="请输入"  onKeyPress={this.keyPress}/>)}
        </FormItem>
        <FormItem label="地址">
          {getFieldDecorator('address', {
            initialValue: searchParams.address,
          })(<Input style={{ width: '150px' }} placeholder="请输入"  onKeyPress={this.keyPress}/>)}
        </FormItem>
        {[{key:'min_consumption',name:"最小用水量"},
          {key:'max_consumption',name:"最大用水量"},
          {key:'min_signal_intensity',name:"最小信号强度"},
          {key:'max_signal_intensity',name:"最大信号强度"},
          {key:'min_snr',name:"最小SNR"},
          {key:'max_snr',name:"最大SNR"}].map((item,index)=>{
            return   <FormItem label={item.name} key={item.key}>
              {getFieldDecorator(item.key, {
                initialValue: searchParams[item.key],
              })(<Input style={{ width: '80px' }} placeholder="请输入"  onKeyPress={this.keyPress}/>)}
            </FormItem>
        })}
        <FormItem>
          <Button
            type="primary"
            icon='search'
            onClick={() => {
              const { form } = this.props;
              form.validateFields((err, fieldsValue) => {
                if (err) return;

                this.handleSearch({
                  page: 1,
                  per_page: searchParams.per_page,
                  ...fieldsValue,
                  date: moment(fieldsValue.date).format('YYYY-MM-DD'),
                });

              });
            }}
          >
            查询
          </Button>
          <Button style={{ marginLeft: 8 }} icon='redo' onClick={this.handleFormReset}>
            重置
          </Button>
        </FormItem>

      </Form>
    );
  }
  keyPress=(e)=>{
    let theEvent = e || window.event;
    let code = theEvent.keyCode || theEvent.which || theEvent.charCode;
    if (code === 13) {
      e.preventDefault();
      console.log('key press')
      const {
        devices: { searchParams },
      } = this.props;
      const { form } = this.props;
      form.validateFields((err, fieldsValue) => {
        if (err) return;

        this.handleSearch({
          page: 1,
          per_page: searchParams.per_page,
          ...fieldsValue,
          date: moment(fieldsValue.date).format('YYYY-MM-DD'),
        });

      });
    }
  }
  handleAdd = () => {
    const formValues = this.AddForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    const that = this;
    this.props.dispatch({
      type: 'devices/add',
      payload: {
        ...formValues,
      },
      callback() {
        message.success('新建设备成功');
        that.setState({
          addModal: false,
        });
        const {
          devices: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };

  handleFormReset = () => {
    const { form } = this.props;
    form.resetFields();
    this.handleSearch({
      date: moment().subtract(1, "day").format("YYYY-MM-DD"),
      meter_number: '',
      user_number: '',
      address: '',
      opened_account:'',
      company_id:'',
      vendor_id: '',
      status: '0',
      page: 1,
      per_page: 50,
      min_consumption:'',
      max_consumption:'',
      min_signal_intensity:'',
      max_signal_intensity:'',
      min_snr:'',
      max_snr:'',
    });
  };

  renderStatus = (val) => {
    let type = '';
    let color = '';
    let text = '';
    switch (val) {
      case -1:
        type = 'close-circle', color = '#eb2f96', text = '离线';
        break;
      case 1:
        type = 'check-circle', color = '#52c41a', text = '正常';
        break;
      default:
        type = 'close-circle', color = '#eb2f96', text = '异常';
        break;
    }
    return <Fragment> <Icon type={type} theme="twoTone" className="table-icon" twoToneColor={color}/>{text}</Fragment>;
  };
  renderObserve = (val) => {
    let type = '';
    let color = '';
    let text = '';
    switch (val) {
      case -1:
        type = 'close-circle', color = '#eb2f96', text = '关闭';
        break;
      case 1:
        type = 'check-circle', color = '#52c41a', text = '开启';
        break;
      default:
        break;
    }
    return <Fragment> <Icon type={type} theme="twoTone" className="table-icon" twoToneColor={color}/>{text}</Fragment>;
  };
  getOption = () => {
    const {
      devices: { pickRowData },
    } = this.props;
    const data = pickRowData.data.data;
    let Date = [];
    let Data = [];
    let diffData = [];
    let errDataIndex = [];
    let warmDataIndex = [];
    let difference_value = 0;
    forEach(data, (value, index) => {
      Date.push(value.date);
      Data.push(value.value);
      if (value.status !== 1) {
        errDataIndex.push(index);
      }
      diffData.push(value.consumption);
    });
    let option = {
      background: 'rgba(0,0,0,1)',
      color: ['#00a925', '#fe5810'],
      animation: false,
      title: {
        text: `${pickRowData.address?pickRowData.address:pickRowData.number} 近一个月状态`,
      },
      tooltip: {
        trigger: 'axis',
      },
      legend: {
        data: ['水表读数', '用水量'],
      },
      xAxis: [
        {
          type: 'category',
          data: Date,
          axisPointer: {
            type: 'shadow',
          },
        },
      ],
      yAxis: [
        {
          type: 'value',
          name: '水表读数(柱状图)',
          axisLabel: {
            formatter: '{value}(m3)',
          },
        },
        {
          type: 'value',
          name: '用水量(折线图)',
          axisLabel: {
            formatter: '{value}(m3)',
          },
          splitLine: {
            show: false,
          },
        },
      ],
      grid: {
        top: '22%',
        left: '2%',
        right: '2%',
        bottom: '4%',
        containLabel: true,
      },
      series: [
        {
          name: '水表读数',
          type: 'bar',
          data: Data,
          itemStyle: {
            normal: {
              color: function(value) {
                if (errDataIndex.indexOf(value.dataIndex) >= 0) {
                  return '#c23531';
                } else {
                  return '#00a925';
                }
              },
            },
          },
        },
        {
          name: '用水量',
          type: 'line',
          yAxisIndex: 1,
          symbolSize: 8,
          data: diffData,
          smooth: true,
          itemStyle: {
            normal: {
              color: '#fe5810',
            },
          },
          markLine: {
            silent: false,
            lineStyle:{
              color:'#3cde00',
              type:'dashed',
            },
            label: {
              formatter: '{b} {c}',
              position: 'middle',
              color:'#fff',
              fontsize:18,
              backgroundColor: '#68a8ff',
              padding: [6, 4,4]
            },
            data: [{
              name: '日用水平均值',
              type: "average"
            }],
          }
        },
      ],
    };
    return option;
  };
  renderValueStatus = (val) => {
    let status = 'success';
    let explain = '';
    switch (val) {
      case -5:
        status = 'error';
        explain = '接入异常';
        break;
      case -4:
        status = 'error';
        explain = '错报';
        break;
      case -3:
        status = 'error';
        explain = '抄表失败';
        break;
      case -2:
        status = 'warning';
        explain = '漏报';
        break;
      case -1:
        status = 'warning';
        explain = '未上报';
        break;
      default:
        status = 'success';
        explain = '正常';
    }
    return (
      <p>
        <Badge status={status}/>{explain}
      </p>
    );
  };
  handleExportMeter=()=>{
    const {
      devices: { searchParams },
    } = this.props;
    console.log('searchParams',searchParams)
    download(`${config.prefix}/meter_analysis_files?Authorization=Bearer ${sessionStorage.getItem('token')}&order_direction=desc&${formateObjToParamStr2({...searchParams,
      company_ids:getEW(searchParams.company_ids)})}`)

  }
  render() {
    const that = this;
    const {
      devices: { data, loading, tableY, meta, searchParams, selectedRowKeys, status_count, total_consumption },
      global: { gridTableW },
    } = this.props;

    const defaultColumnProperties = {
      resizable: true,
    };
    const columns = [
      {
        name: '序号',
        width: 50,
        key: '_index',
        frozen: true,
        formatter: (event) => {
          const {
            devices: { meta },
          } = this.props;
          return <p className={'index'}>{((meta.current_page - 1) * meta.per_page) + (event.value + 1)}</p>;
        },
      },
      {
        name: '水表号',
        width: 150,
        key: 'meter_number',
        frozen: true,
      },
      {
        name: '上传状态',
        key: 'status',
        width: 100,
        formatter: (e) => {
          return that.renderValueStatus(e.value);
        },
      },
      {
        name: '用水量(m3)',
        key: 'consumption',
        width: 150,
        formatter: (e) => {
          return <Fragment><span style={{ display: 'inline-block', minWidth: '35px', width: '35px' }}>{e.value}</span>
            <Progress percent={e.value * 100} size="small" status="active"/></Fragment>;
        },
      },
      {
        name: '抄表时间',
        key: 'upload_time',
        width: 150,
      },
      {
        name: '水表读数(m3)',
        key: 'value',
        width: 100,
      },
      {
        name: '上次有效上传时间',
        key: 'last_normal_upload_time',
        width: 150,
      },
      {
        name: '上次有效水表读数(m3)',
        key: 'last_normal_value',
        width: 150,
      },
      {
        name: '阀门状态',
        key: 'valve_status',
        width: 100,
        formatter: (event) => {
          return renderValveOpen(event.value,event.row.is_valve);
        },
      },
      {
        name: '安装地址',
        key: 'address',
        width: 150,
      },
      {
        name: '水表厂商名称',
        key: 'vendor_name',
        width: 130,
      },
      {
        name: '操作',
        width: 100,
        key: 'right',
        classname: 'operate',
        formatter: (event) => <Fragment>
          <Button
            type="primary"
            size="small"
            icon="eye"
            onClick={(e) => {
              this.setState({
                editRecord: event.row,
                infoModal: true,
              });
            }
            }
          >详情
          </Button>
        </Fragment>,
      },
    ].map(c => ({ ...defaultColumnProperties, ...c }));

    let totalWidth = 0;
    for (let i = 0; i < columns.length; i++) {
      totalWidth += columns[i].width;
    }
    if (totalWidth < gridTableW) {
      columns[columns.length - 1].width = columns[columns.length - 1].width + gridTableW - totalWidth;
    }
    const RowRenderer = ({ renderBaseRow, ...props }) => {
      const className = props.row.status !== 1 ? 'table-error' : '';
      return <div className={className}>{renderBaseRow(props)}</div>;
    };
    return <div className="custom-card">
      <div className="table-title"><span className={'title-item'}>水表分析</span>
      </div>
      <div className="table-page table-page-flex">
        <div className="table-page-right">
          <div className="table-info">
            <div className="table-info-item  animated fadeInLeft">
              <p>水表总数量(个)</p>
              <h4>{status_count.total_count}</h4>
            </div>
            <div className="table-info-item  animated fadeInLeft">
              <p>用水量(m3)</p>
              <h4>{total_consumption.cold_meter && total_consumption.cold_meter.consumption}</h4>
            </div>
            <div className="table-info-item  animated fadeInLeft">
              <p className={'success'}>水表正常数量(个)</p>
              <h4 className={'success'}>{status_count.normal_upload_count}</h4>
            </div>
            <div className="table-info-item  animated fadeInLeft">
              <p className={'success'}>水表正常率(%)</p>
              <h4 className={'success'}>{status_count.normal_upload_rate}</h4>
            </div>

            <div size="large" className="table-info-right-item  animated fadeInRight">
            {
              find(this.permissions, { name: 'meter_data_export' }) &&
              <Tooltip title={'请先查询一次再导出'}>
              <Button
                icon="export"
                style={{ marginLeft: 8 }}
                type="primary"
                onClick={
                  () => {
                    this.handleExportMeter()
                  }
                }
              >
                导出水表数据
              </Button>
              </Tooltip>

            }

            </div>
          </div>
          <div className="table-condition">{this.renderSimpleForm()}</div>
          <div className={'table-data-content'}>
            <ReactDataGrid
              columns={columns}
              rowGetter={i => {
                return { ...data[i], _index: i };
              }}
              rowsCount={data.length}
              minHeight={tableY}
              rowSelection={{
                showCheckbox: false,
                enableShiftSelect: true,
                selectBy: {
                  indexes: selectedRowKeys,
                },
              }}
              onRowClick={
                (index, row) => {
                  console.log('row', row);
                  if (!row) {
                    return;
                  }
                  this.props.dispatch({
                    type: 'devices/changeSelectRow',
                    payload: {
                      selectedIndex: [index],
                      row: row,
                    },
                  });
                }
              }

            />
            {
              loading && <Loading/>
            }
          </div>
        </div>


      </div>
      <div className="table-pagination">
        <MyPagination searchCondition={{ ...searchParams }}
                      resetScrollY={() => {
                        console.log('resetScrollY');
                        const {
                          devices: { scrollData },
                        } = this.props;
                        const table = document.querySelector('.react-grid-Canvas');
                        setTimeout(() => {
                          table.scrollTop = 0;
                          table.scrollLeft = scrollData.x;
                        }, 0);

                      }}
                      meta={meta} handleSearch={this.handleSearch}/>
      </div>
      <div className="bottom-analysis"><ReactEcharts
        option={this.getOption()}
        style={{ height: '100%', width: '100%' }}
        theme='my_theme'
        //onChartReady={this.onChartReadyCallback}
        //onEvents={EventsDict}
      />
      </div>
      <Drawer
        title={`${this.state.editRecord.meter_number} 详情`}
        placement="right"
        closable={false}
        destroyOnClose
        onClose={() => {
          this.setState({
            infoModal: false,
            editRecord: {},
          });
        }}
        width={700}
        visible={this.state.infoModal}
      >
        <Detail id={this.state.editRecord.meter_id}></Detail>
      </Drawer>
    </div>;
  }
}

export default BasicList;
